<template>
  <div class="home-wrap">
    <el-row :gutter="20" type="flex" justify="space-between">
      <el-col :span="16">
        <div class="content-common" style="width: 55%">
          <div class="search-top">
            <el-form :label-position="'top'" :inline="true" :model="query">
              <el-form-item label="测站">
                <el-input v-model="query.stnm" placeholder="请输入" clearable></el-input>
              </el-form-item>
              <el-form-item class="search-btn">
                <el-button
                  class="table-btn-blur"
                  @click="
                    page.currentPage = 1;
                    getData();
                  "
                  >查询</el-button
                >
              </el-form-item>
            </el-form>
            <div class="right-search">
              <el-button class="table-btn-plain" @click="handlerExcelDownLoad">Excel导出</el-button>
              <!-- <el-button type="primary" @click="handleAdd()">新增</el-button> -->
            </div>
          </div>
          <el-table :data="tableData.slice((page.currentPage - 1) * 10, page.currentPage * 10)" border class="table-common" header-cell-class-name="table-header">
            <el-table-column type="index" width="55" label="序号"></el-table-column>
            <el-table-column align="center" prop="userName" label="人员姓名"></el-table-column>
            <el-table-column align="center" prop="stnm" label="测站"></el-table-column>
            <el-table-column align="center" prop="specificDate" label="日期"></el-table-column>
            <el-table-column align="center" prop="weekDay" label="星期"></el-table-column>
            <el-table-column align="center" prop="clockInTime" label="上班打卡时间"></el-table-column>
            <el-table-column align="center" prop="clockOffTime" label="下班打卡时间"></el-table-column>
            <el-table-column align="center" prop="coordinate" label="签到点位"></el-table-column>
            <el-table-column align="center" prop="status" label="状态"></el-table-column>
            <el-table-column label="操作" width="200" align="center">
              <template #default="scope">
                <!-- <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button> -->
                <el-button type="danger" class="table-btn-delete" @click="handleDelete(scope.row)">删除</el-button>
                <!-- <el-button type="success" @click="tomingxi(scope.row)">查看明细</el-button> -->
              </template>
            </el-table-column>
          </el-table>

          <el-row type="flex" justify="end" style="margin-top: 20px">
            <el-pagination background v-model:currentPage="page.currentPage" @current-change="getData" layout="prev,total, pager, next" :total="page.totalSize"> </el-pagination>
          </el-row>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="content-common">
          <el-calendar v-model="calenderDate"> </el-calendar>
        </div>
      </el-col>
    </el-row>
    <!-- 编辑弹出框 -->
    <el-dialog :title="logTitle" v-model="editVisible" width="800px">
      <el-form ref="form" :rules="rules" :model="form" label-width="160px" label-position="top">
        <el-row type="flex" justify="space-between">
          <el-col :span="7">
            <el-form-item label="测站" prop="stnm">
              <el-select v-model="form.stnm" filterable placeholder="请选择">
                <el-option v-for="item in stationData" :key="item.stnm" :label="item.stnm" :value="item.stnm"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="签到类型" prop="clockType">
              <el-select v-model="form.clockType" filterable placeholder="请选择">
                <el-option v-for="item in clockTypeList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="签到时间" prop="specificDate">
              <el-date-picker
                value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
                type="datetime"
                placeholder="选择时间"
                v-model="form.specificDate"
                style="width: 100%"
                :picker-options="startTimeOptions"
                ref="start"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="space-between">
          <el-col :span="7">
            <el-form-item label="签到定位" prop="coordinate">
              <el-input v-model="form.coordinate" placeholder="签到定位"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="备注">
              <el-input v-model="form.remark" placeholder="备注"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7"> </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="saveEdit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import {
  sysdictviewlistDictItem,
  viewPageStationInfo,
  pageAttendanceRecord, //分页查询
  saveAttendanceRecord, //新增编辑打卡记录
  delAttendanceRecord, //删除打卡记录
  exportAttendanceRecord, //导出打卡记录列表
  listDailyRecord //列表查询日常考勤情况（包含所有站点工作人员，未签到则没有签到详情信息）
} from '../../../api/index';
import moment from 'moment';
export default {
  name: 'zhengbianguancao',
  data() {
    return {
      tijiaorule: {
        status: [{ required: true, message: '必填项', trigger: 'change' }]
      },
      rules: {
        stnm: [{ required: true, message: '必填项', trigger: 'change' }]
      },
      shenpilog: false,
      globalUser: [],
      page: {
        currentPage: 1,
        pageSize: 10,
        totalPage: 0,
        totalSize: 0
      },
      query: {
        specificDate: ''
      },
      excelllog: false,
      formInline: {},
      tableData: [],
      clockTypeList: [
        { label: '上班', value: 1 },
        { label: '下班', value: 2 }
      ],
      editVisible: false,
      logTitle: '',
      pageTotal: 0,
      form: {
        clockTime: '', //打卡时间（HH:mm:ss）
        clockType: '', //打卡类型（1上班，2下班）
        coordinate: '', //签到点坐标
        id: '', //主键id
        remark: '', //备注
        specificDate: '', //日期（yyyy-MM-dd）
        stnm: '', //测站
        userCode: JSON.parse(sessionStorage.getItem('userInfo')).userNo //用户编号
      },
      stationData: [],
      checkArr: [],
      tijiaoform: {
        status: 1
      },
      selnow: {},
      startTimeOptions: {
        disabledDate: (time) => {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000;
        }
      },
      isView: false,
      calenderDate: new Date()
    };
  },
  watch: {
    calenderDate(newVal, oldVal) {
      // 格式化 因为绑定的数组不是我们想用的，这里以2022-22-22这种格式作为演示
      let date = this.formatDate(newVal);
      this.query.specificDate = date;
      // 这里就是我们处理数据，调用接口的位置
      this.getData();
    }
  },
  created() {
    this.query.specificDate = new Date();
    this.query.specificDate = this.formatDate(this.query.specificDate);
    this.globalUser = globalUser;
    this.getData();
    this.getstationData();
    this.getchecktype();
  },
  methods: {
    formatDate(date) {
      const value = new Date(date);
      const year = value.getFullYear();
      const month = (value.getMonth() + 1).toString().padStart(2, '0');
      const day = value.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    tomingxi(item) {
      this.form = item;
      this.logTitle = '查看打卡';
      this.editVisible = true;
    },
    getchecktype() {
      let that = this;
      sysdictviewlistDictItem({
        dictCode: 'ZD-000004'
      })
        .then((e) => {
          that.checkArr = e.object;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    shenpi(item) {
      this.tijiaoform.reviewer = item.reviewer;
      this.tijiaoform.relatedNo = item.recordNo;
      this.tijiaoform.approveType = 'R2';
      this.shenpilog = true;
      this.selnow = item;
    },
    getstationData() {
      let data = {
        currentPage: 1,
        pageSize: 1000
      };
      viewPageStationInfo(data).then((res) => {
        this.stationData = res.object.dataList.filter((item) => {
          return item.stType == systype;
        });
      });
    },
    //导出
    async handlerExcelDownLoad() {
      let url = globalVar.xiaoliuyubaseURL + '/soilWater/manage/attendance/export/exportAttendanceRecord';
      var options = {
        url: url,
        method: 'post',
        responseType: 'blob',
        headers: {
          Authorization: sessionStorage.getItem('token')
        }
      };
      axios(options).then((res) => {
        if (res) {
          const link = document.createElement('a');
          let blob = new Blob([res.data], { type: 'application/vnd.ms-excel' }); //生成blob对象
          link.style.display = 'none';
          link.href = URL.createObjectURL(blob);
          const fileName = '考勤打卡记录表';
          link.setAttribute('download', `${fileName}` + '.xlsx'); //下载的文件名以及文件格式
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        } else {
          console.log('下载失败');
        }
      });
    },
    getData() {
      let that = this;
      let data = {
        currentPage: this.page.currentPage,
        pageSize: 10,
        specificDate: this.query.specificDate || ''
      };
      listDailyRecord(data).then((res) => {
        this.tableData = res.object;
        for (let i = 0; i < that.tableData.length; i++) {
          if (that.tableData[i].specificDate == null || that.tableData[i].specificDate == '') {
            that.tableData[i].specificDate = this.query.specificDate;
          }
        }
        this.page.totalSize = res.object.length;
      });
    },
    // 触发搜索按钮
    handleSearch() {
      this.getData();
    },
    // 删除操作
    handleDelete(row) {
      // 二次确认删除
      this.$confirm('确定要删除吗？', '提示', {
        type: 'warning'
      })
        .then(() => {
          delAttendanceRecord({
            id: row.id
          }).then((e) => {
            this.$message.success('删除成功');
            this.getData();
          });
        })
        .catch(() => {});
    },

    // 编辑操作
    handleEdit(row) {
      let form = row;
      form.clockType = row.recordType;
      this.logTitle = '编辑打卡';
      form.specificDate = row.recordType == 1 ? row.specificDate + ' ' + row.clockInTime : row.specificDate + ' ' + row.clockOffTime;
      this.form = form;
      this.editVisible = true;
    },
    handleAdd() {
      this.logTitle = '新增打卡';
      this.editVisible = true;
    },
    // 保存编辑
    saveEdit() {
      let that = this;
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let form = that.form;
          form.clockTime = that.form.specificDate.split(' ')[1];
          form.specificDate = that.form.specificDate.split(' ')[0];
          saveAttendanceRecord(form).then((e) => {
            this.editVisible = false;
            this.$message.success('操作成功');
            this.getData();
          });
        } else {
          return false;
        }
      });
    }
  }
};
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.mr10 {
  margin-right: 10px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
.table-btn-plain {
  background: #fff !important;
  border: 1px solid #3f8cff !important;
  border-radius: 2px;
  color: #3f8cff !important;
  font-size: 14px;
}
.search-btn {
  margin-top: 30px;
  width: auto !important;
}
.table-btn-blur {
  background: #3f8cff !important;
  border: 1px solid #3f8cff !important;
  border-radius: 2px;
  color: #fff !important;
}
.table-btn-delete {
  background: #ff544e !important;
  border: 1px solid #ff544e !important;
  border-radius: 2px;
  color: #fff !important;
}
.content-common {
  bottom: 28px;
  top: 109px;
  overflow-y: auto;
  overflow-x: hidden;
  position: fixed;
}

.home-wrap {
  min-height: 100%;
  height: auto !important;
  height: 100%;
  position: relative;
  width: 100%;
  overflow-x: hidden;
}
</style>

